#include <dm/export.hpp>

#define DM_API_SCADA DM_API_EXPORT

#include <dm/scada/model/loader.hpp>
#include <dm/os/log/logger.hpp>
#include <dm/string/stringlist.hpp>

namespace dm{
namespace scada{
namespace model{

static const char* logModule = "CLoader.model.scada.dm";

CLoader::CLoader( dm::os::CDb& db ):m_db(db){
    log().debug(THISMODULE "创建对象");
}

/**
 * 设置加载全部记录
*/
bool CLoader::setAll(){
    m_resultSet = m_db.query("select id,name,descr,sound,version from t_model order by id");
    return true;
}

/**
 * 设置加载指定ID记录
*/
bool CLoader::setId( const id_t& id ){
    char sql[128];
    std::sprintf(sql,"select id,name,descr,sound,version from t_model where id=%d",id);
    m_resultSet = m_db.query(sql);
    return true;
}

/**
 * 设置加载指定名称记录
*/
bool CLoader::setName( const char* name ){
    char sql[128];
    std::sprintf(sql,"select id,name,descr,sound,version from t_model where name='%s'",name);
    m_resultSet = m_db.query(sql);
    return true;
}

/**
 * 添加已经加载过的记录
*/
bool CLoader::addALoaded( SModelInfo& info ){
    m_loaded.push_back(info.id);
    return true;
}

/**
 * 过滤已经加载过的记录
*/
bool CLoader::filterLoaded(){
    if( m_loaded.size()<=0 )
        return setAll();

    dm::string::CStringList tempList;
    tempList.append("select id,name,descr,sound,version from t_model where id not in (");

    char sqlTmp[20];
    bool f = false;
    for( std::vector<id_t>::iterator it=m_loaded.begin();it!=m_loaded.end();++it ){
        if( f )
            std::sprintf(sqlTmp,",%d",*it);
        else
            std::sprintf(sqlTmp,"%d",*it);
        tempList.append(sqlTmp);
    }

    tempList.append(") order by id");
    
    m_loaded.clear();

    m_resultSet = m_db.query(tempList.toString().c_str());

    return true;
}

bool CLoader::next(){
    return m_resultSet?m_resultSet->next():false;
}

bool CLoader::loadRecord( SModelInfo& info ){
    if( !m_resultSet )
        return false;

    info.id = m_resultSet->asInt64(0,-1);
    info.name = m_resultSet->asString(1,"NULL");
    info.desc = m_resultSet->asString(2,"未定义");
    info.sound = m_resultSet->asString(3,"");
    info.magic = 0; // 未初始化记录

    return true;
}

}
}
}